use askama_axum::{IntoResponse, Template};
use axum::{extract::{Path, State}, response::{Html, Redirect}, Form};
use tower_cookies::Cookies;
use tower_sessions::Session;
use crate::{core::xerror::{XErrors, GLOBALERROR}, types::backend::admin_type::AdminDetail};
use crate::{core::{pwd::get_password, AppState}, types::common::Breadcrumb};
use crate::services::backend::admin_service::AdminService;
use crate::types::backend::admin_type::{AdminForm, AdminRow};
use super::{AdminSession, ErrorTemplate};

#[derive(Template)]
#[template(path = "backend/admin/list.html")]
struct AdminListTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    list: Vec<AdminRow>,
}


#[derive(Template)]
#[template(path = "backend/admin/form.html")]
struct AdminFormTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    data: AdminForm,
    url: String, // action url 
}

#[derive(Template)]
#[template(path = "backend/admin/detail.html")]
struct AdminDetailTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    data: AdminDetail
}

/// 获取所有管理员
pub async fn admins_handler(State(state): State<AppState>, session: Session) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let res = AdminService::get_all_admins(&state.db).await;
    let breadcrumb = Breadcrumb {
        title: "管理员管理".to_string(),
        sub_title: "管理员列表".to_string(),
    };
   
    match res {
        Ok(list) => {
            let template = AdminListTemplate {
                auth,
                breadcrumb,
                list: list,
            };
            Html(template.render().unwrap())
        },
        Err(e) => {
            let template = ErrorTemplate {
                msg: e.to_string()
            };
            Html(template.render().unwrap())
        }
    }
   
}

/// 添加管理员表单
pub async fn add_admin_handler(session: Session) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let breadcrumb = Breadcrumb {
        title: "管理员管理".to_string(),
        sub_title: "添加管理员".to_string(),
    };
    let template = AdminFormTemplate {
        auth,
        breadcrumb,
        data: AdminForm{
            name: "".to_string(), 
            password: "".to_string()
        },
        url: "/backend/admin/create".to_string(),
    };
    return Html(template.render().unwrap());
}


/// 添加管理员操作
pub async fn create_admin_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Form(form): Form<AdminForm>) -> Redirect {
    let error = XErrors::new();
    if form.name.is_empty() || form.password.is_empty() {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to("/backend/admin/create");
    }
    let pwd = get_password(&form.password);
    let new_form = AdminForm {
        name: form.name,
        password: pwd,
    };
    let res = AdminService::insert_admin(&state.db, &new_form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::ADDSUCCESS, "".to_string());
            return Redirect::to("/backend/admin/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::ADDFAILED, db_error);
            return Redirect::to("/backend/admin/list");
        }
    }
}

/// 修改管理员表单
pub async fn edit_admin_handler(State(state): State<AppState>, session: Session, Path(id): Path<i64>) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let res = AdminService::get_admin_by_id(&state.db, id).await;
    let breadcrumb = Breadcrumb {
        title: "管理员管理".to_string(),
        sub_title: "修改管理员".to_string(),
    };
    match res {
        Ok(data) => {
            let admin_form = AdminForm {
                name: data.name,
                password: "".to_string(),
            };
            let template = AdminFormTemplate {
                auth,
                breadcrumb,
                data: admin_form,
                url: format!("/backend/admin/edit/{}", id),   
            };
            return Html(template.render().unwrap());
        },
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string(),
            };
            return Html(template.render().unwrap());
        }
    }
}

/// 修改管理员操作
pub async fn update_admin_handler(
    State(state): State<AppState>, 
    cookies: Cookies, 
    Path(id): Path<i64>,
    Form(form): Form<AdminForm>) -> Redirect {
    let error = XErrors::new();
    // 名称不能为空
    if form.name.is_empty() || form.password.is_empty() {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to(format!("/backend/admin/edit/{}", id).as_str());
    }

    let pwd = get_password(&form.password);
    let new_form = AdminForm {
        name: form.name,
        password: pwd,
    };
    let res = AdminService::update_admin(&state.db, id, &new_form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::UPDATESUCCESS, "".to_string());
            return Redirect::to("/backend/admin/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::UPDATEFAILED, db_error);
            return Redirect::to("/backend/admin/list");
        }
    }
}

/// 删除管理员操作
pub async fn delete_admin_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Path(id): Path<i64>) -> Redirect {
    let error = XErrors::new();
    // 是否存在
    let exist = AdminService::exist_admin_by_id(&state.db, id).await;
    let total = match exist {
        Ok(total) => total,
        Err(_) => 0,
    };
    if total == 0 {
        error.set_cookie_error(cookies, GLOBALERROR::RECORDNOTFOUND, "".to_string());
        return Redirect::to("/backend/admin/list");
    }
    let res = AdminService::delete_admin(&state.db, id).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::DELETESUCCESS, "".to_string());
            return Redirect::to("/backend/admin/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::DELETEFAILED, db_error);
            return Redirect::to("/backend/admin/list");
        }
    }
}


pub async fn detail_admin_handler(State(state): State<AppState>, session: Session) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let breadcrumb = Breadcrumb {
        title: "管理员管理".to_string(),
        sub_title: "查看管理员".to_string(),
    };
    let admin_res = AdminService::get_admin_by_id(&state.db, auth.id).await;
    match admin_res {
        Ok(data) => {
            let template = AdminDetailTemplate {
                auth,
                breadcrumb,
                data
            };
            return Html(template.render().unwrap());
        },
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string(),
            };
            return Html(template.render().unwrap());
        }
    }
    
}
 